<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Promotion, Search, Plus, Edit, Delete, Picture, Link } from '@element-plus/icons-vue'
import request from '@/utils/request'

const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''

interface Advertisement {
  id: string
  title: string
  description?: string
  imageUrl: string
  linkUrl?: string
  sortOrder: number
  isActive: boolean
  startDate?: string
  endDate?: string
  clickCount: number
  createdAt: string
  updatedAt: string
}

const searchQuery = ref('')
const loading = ref(false)
const advertisementList = ref<Advertisement[]>([])
const showDialog = ref(false)
const editingId = ref<string | null>(null)

const advertisementForm = reactive({
  title: '',
  description: '',
  imageUrl: '',
  linkUrl: '',
  sortOrder: 0,
  isActive: true,
  startDate: '',
  endDate: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10) // 移动端每页显示较少
const total = ref(0)

async function fetchAdvertisements() {
  loading.value = true
  try {
    const { data } = await request.get('/api/admin/advertisements', {
      params: {
        page: currentPage.value,
        limit: pageSize.value,
        search: searchQuery.value || undefined
      }
    })
    advertisementList.value = data.advertisements
    total.value = data.total
  } catch (error) {
    ElMessage.error('광고 목록 가져오기 실패')
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  fetchAdvertisements()
}

function resetForm() {
  advertisementForm.title = ''
  advertisementForm.description = ''
  advertisementForm.imageUrl = ''
  advertisementForm.linkUrl = ''
  advertisementForm.sortOrder = 0
  advertisementForm.isActive = true
  advertisementForm.startDate = ''
  advertisementForm.endDate = ''
  editingId.value = null
}

function handleAdd() {
  resetForm()
  showDialog.value = true
}

function handleEdit(ad: Advertisement) {
  advertisementForm.title = ad.title
  advertisementForm.description = ad.description || ''
  advertisementForm.imageUrl = ad.imageUrl
  advertisementForm.linkUrl = ad.linkUrl || ''
  advertisementForm.sortOrder = ad.sortOrder
  advertisementForm.isActive = ad.isActive
  advertisementForm.startDate = ad.startDate ? ad.startDate.split('T')[0] : ''
  advertisementForm.endDate = ad.endDate ? ad.endDate.split('T')[0] : ''
  editingId.value = ad.id
  showDialog.value = true
}

async function handleSave() {
  if (!advertisementForm.title || !advertisementForm.imageUrl) {
    ElMessage.error('제목과 이미지 URL을 입력하세요')
    return
  }

  try {
    const formData = {
      ...advertisementForm,
      startDate: advertisementForm.startDate || null,
      endDate: advertisementForm.endDate || null
    }

    if (editingId.value) {
      await request.put(`/api/admin/advertisements/${editingId.value}`, formData)
      ElMessage.success('업데이트 성공')
    } else {
      await request.post('/api/admin/advertisements', formData)
      ElMessage.success('생성 성공')
    }
    
    showDialog.value = false
    await fetchAdvertisements()
  } catch (error) {
    ElMessage.error(editingId.value ? '업데이트 실패' : '생성 실패')
  }
}

async function handleDelete(ad: Advertisement) {
  try {
    await ElMessageBox.confirm(
      `"${ad.title}" 광고를 삭제하시겠습니까?`,
      '삭제 확인',
      {
        confirmButtonText: '삭제',
        cancelButtonText: '취소',
        type: 'warning',
      }
    )

    await request.delete(`/api/admin/advertisements/${ad.id}`)
    ElMessage.success('삭제 성공')
    await fetchAdvertisements()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('삭제 실패')
    }
  }
}

// 图片上传成功处理
function handleImageSuccess(response: any) {
  advertisementForm.imageUrl = response.coverUrl
  ElMessage.success('이미지 업로드 성공')
}

// 获取图片URL
function getImageUrl(url: string) {
  if (!url) return ''
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  return `${API_BASE_URL}${url}`
}

// 分页处理
function handlePageChange(page: number) {
  currentPage.value = page
  fetchAdvertisements()
}

onMounted(() => {
  fetchAdvertisements()
})
</script>

<template>
  <div class="advertisement-management-view">
    <div class="page-header">
      <div class="header-content">
        <el-icon class="page-icon" size="24">
          <Promotion />
        </el-icon>
        <div class="header-text">
          <h1 class="page-title">광고 관리</h1>
          <p class="page-subtitle">홈페이지 광고 배너를 관리합니다</p>
        </div>
      </div>
    </div>

    <div class="page-content">
      <!-- 搜索栏 -->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="광고 제목으로 검색"
          :prefix-icon="Search"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" :loading="loading" />
          </template>
        </el-input>
      </div>

      <!-- 操作按钮 -->
      <div class="action-section">
        <el-button type="primary" :icon="Plus" @click="handleAdd">
          광고 추가
        </el-button>
      </div>

      <!-- 광고 목록 -->
      <div class="ads-list" v-loading="loading">
        <div v-for="ad in advertisementList" :key="ad.id" class="ad-card">
          <div class="ad-image">
            <img
              v-if="ad.imageUrl"
              :src="getImageUrl(ad.imageUrl)"
              :alt="ad.title"
            />
            <div v-else class="no-image">
              <el-icon><Picture /></el-icon>
              <span>이미지 없음</span>
            </div>
          </div>
          <div class="ad-content">
            <div class="ad-header">
              <h3 class="ad-title">{{ ad.title }}</h3>
              <div class="ad-status">
                <el-tag :type="ad.isActive ? 'success' : 'info'" size="small">
                  {{ ad.isActive ? '활성' : '비활성' }}
                </el-tag>
              </div>
            </div>
            <p v-if="ad.description" class="ad-description">{{ ad.description }}</p>
            <div class="ad-meta">
              <div class="ad-stats">
                <span class="click-count">클릭: {{ ad.clickCount }}</span>
                <span class="sort-order">순서: {{ ad.sortOrder }}</span>
              </div>
              <div class="ad-actions">
                <el-button size="small" :icon="Edit" @click="handleEdit(ad)">
                  편집
                </el-button>
                <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(ad)">
                  삭제
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <div v-if="!loading && advertisementList.length === 0" class="empty-state">
          <el-icon size="48"><Promotion /></el-icon>
          <p>등록된 광고가 없습니다</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination" v-if="total > pageSize">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="editingId ? '광고 편집' : '광고 추가'"
      width="90%"
      :close-on-click-modal="false"
    >
      <el-form :model="advertisementForm" label-position="top">
        <el-form-item label="제목" required>
          <el-input v-model="advertisementForm.title" />
        </el-form-item>
        <el-form-item label="설명">
          <el-input v-model="advertisementForm.description" type="textarea" rows="2" />
        </el-form-item>
        <el-form-item label="이미지" required>
          <div class="image-upload-section">
            <el-upload
              :action="`${API_BASE_URL}/api/admin/uploads/cover`"
              name="cover-upload"
              :with-credentials="true"
              :show-file-list="false"
              :on-success="handleImageSuccess"
            >
              <div v-if="advertisementForm.imageUrl" class="uploaded-image">
                <img :src="getImageUrl(advertisementForm.imageUrl)" alt="광고 이미지" />
              </div>
              <el-button v-else type="primary" :icon="Picture">이미지 업로드</el-button>
            </el-upload>
            <el-input
              v-model="advertisementForm.imageUrl"
              placeholder="또는 이미지 URL을 직접 입력"
              style="margin-top: 8px"
            />
          </div>
        </el-form-item>
        <el-form-item label="링크 URL">
          <el-input v-model="advertisementForm.linkUrl" placeholder="클릭 시 이동할 URL (선택사항)">
            <template #prefix>
              <el-icon><Link /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="정렬 순서">
          <el-input-number v-model="advertisementForm.sortOrder" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="시작일">
          <el-date-picker
            v-model="advertisementForm.startDate"
            type="date"
            placeholder="시작일 선택 (선택사항)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="종료일">
          <el-date-picker
            v-model="advertisementForm.endDate"
            type="date"
            placeholder="종료일 선택 (선택사항)"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="활성화">
          <el-switch v-model="advertisementForm.isActive" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">취소</el-button>
          <el-button type="primary" @click="handleSave">
            {{ editingId ? '업데이트' : '생성' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.advertisement-management-view {
  min-height: 100vh;
  background: #f5f7fa;
}

.page-header {
  background: white;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  position: sticky;
  top: 0;
  z-index: 10;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-icon {
  color: #409eff;
}

.header-text {
  flex: 1;
}

.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.page-content {
  padding: 16px;
}

.search-section {
  margin-bottom: 16px;
}

.action-section {
  margin-bottom: 16px;
}

.ads-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ad-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 12px;
}

.ad-image {
  width: 80px;
  height: 45px;
  border-radius: 4px;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.ad-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
  color: #c0c4cc;
  font-size: 12px;
}

.ad-content {
  flex: 1;
  min-width: 0;
}

.ad-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.ad-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ad-description {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.ad-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ad-stats {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #909399;
}

.ad-actions {
  display: flex;
  gap: 8px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-state p {
  margin: 8px 0 0 0;
  font-size: 14px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.image-upload-section {
  width: 100%;
}

.uploaded-image {
  width: 120px;
  height: 68px;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
}

.uploaded-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
